from django.shortcuts import render,render_to_response
from django.http  import HttpResponse,HttpResponseRedirect
import qrcode
import configure
import shutil
import datetime,time
from pay.models import *

# Create your views here.

def test(request):
    name = request.GET['name']
    print name
    return HttpResponse(name)

def index(request):
    qr = qrcode.QRCode(    
    version=1,    
    error_correction=qrcode.constants.ERROR_CORRECT_L,    
    box_size=10,    
    border=4, 
    ) 
    '''
    ip = config.get_ip()
    port = config.get_port()
    url = ip+":"+port+"/pay/"
    '''
    data = str(int(time.time()))
    qr.add_data(data);
    qr.make(fit=True)  
    img = qr.make_image()
    img.save('pic.png')
    shutil.move("pic.png","./static/pic.png");
    #return HttpResponse("index")
    return render_to_response("index.html")


def check(request):
    tmp_passwd = request.GET['passwd']
    tmp_position_id = request.GET['position']
    tmp_timestamp = request.GET['timestamp']
    tmp_emei = request.GET['emei']
    with open('private.pem') as private_file:
        p = private_file.read()
        private_key = rsa.PrivateKey.load_pkcs1(p)
        decrypt_passwd = rsa.decrypt(tmp_passwd,private_key)
        #TODO
        if decrypt_passwd == tmp_emei:
            tmp_user = pay_user.objects.filter(emei = tmp_emei)
            if not tmp_user:
               return HttpResponse("no")
            date_array = datetime.datetime.utcfromtimestamp(int(tmp_timestamp))
            onedayago_array = date_array-detatime.timedelta(day=1)
            onedayago_timestamp = int(time.mktime(onedayago.timetuple()))
            if(tmp_user.timestamp > onedayago_timestamp):
                return HttpResponse("yes")
            else:
                return HttpResponse("timeout")
        else:
            #TODO
            return HttpResponse("bad request")

    


def register(request):
    emei = request.GET['emei']
    position_id = request.GET['position']
    timestamp = request.GET['timestamp']
    user = pay_user()
    user.emei = emei
    user.position_id = position_id
    user.time = timestamp
    user.save()
    return HttpResponse("ok")
